package com.ruoyi.flowable.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.flowable.common.constant.ProcessConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.flowable.common.enums.FlowComment;
import com.ruoyi.flowable.domain.vo.FlowTaskVo;
import com.ruoyi.flowable.flow.FlowableUtils;
import com.ruoyi.flowable.service.ISysFormService;
import com.ruoyi.system.domain.FlowProcDefDto;
import com.ruoyi.flowable.factory.FlowServiceFactory;
import com.ruoyi.flowable.service.IFlowDefinitionService;
import com.ruoyi.flowable.service.ISysDeployFormService;
import com.ruoyi.system.domain.SysForm;
import com.ruoyi.system.mapper.FlowDeployMapper;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysPostService;
import com.ruoyi.system.service.ISysUserService;
import liquibase.pro.packaged.S;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.flowable.bpmn.model.BpmnModel;
import org.flowable.bpmn.model.FlowElement;
import org.flowable.bpmn.model.Process;
import org.flowable.bpmn.model.StartEvent;
import org.flowable.engine.FormService;
import org.flowable.engine.repository.Deployment;
import org.flowable.engine.repository.ProcessDefinition;
import org.flowable.engine.repository.ProcessDefinitionQuery;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.image.impl.DefaultProcessDiagramGenerator;
import org.flowable.task.api.Task;
import org.flowable.task.service.impl.persistence.entity.TaskEntityImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * 流程定义
 *
 * @author Tony
 * @date 2021-04-03
 */
@Service
@Slf4j
public class FlowDefinitionServiceImpl extends FlowServiceFactory implements IFlowDefinitionService {

    @Resource
    private ISysDeployFormService sysDeployFormService;

    @Resource
    private ISysFormService sysFormService;

    @Resource
    private ISysUserService sysUserService;

    @Resource
    private ISysDeptService sysDeptService;

    @Resource
    private FlowDeployMapper flowDeployMapper;

    private static final String BPMN_FILE_SUFFIX = ".bpmn";

    @Override
    public boolean exist(String processDefinitionKey) {
        ProcessDefinitionQuery processDefinitionQuery
                = repositoryService.createProcessDefinitionQuery().processDefinitionKey(processDefinitionKey);
        long count = processDefinitionQuery.count();
        return count > 0 ? true : false;
    }


    /**
     * 流程定义列表
     *
     * @param pageNum  当前页码
     * @param pageSize 每页条数
     * @return 流程定义分页列表数据
     */
    @Override
    public Page<FlowProcDefDto> list(String name,Integer category, Integer pageNum, Integer pageSize) {
        Page<FlowProcDefDto> page = new Page<>();
        PageHelper.startPage(pageNum, pageSize);
        final List<FlowProcDefDto> dataList = flowDeployMapper.selectDeployList(name,category);
        page.setTotal(new PageInfo(dataList).getTotal());
        page.setRecords(dataList);
        return page;
    }

    /**
     * 可发起任务列表
     *
     * @param name
     * @param category
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public Page<FlowProcDefDto> applyList(String name, Integer category, Integer pageNum, Integer pageSize) {
        Page<FlowProcDefDto> page = new Page<>();
        PageHelper.startPage(pageNum, pageSize);
        final List<FlowProcDefDto> dataList = flowDeployMapper.selectApplyList(name,category);
        page.setTotal(new PageInfo(dataList).getTotal());
        page.setRecords(dataList);
        return page;
    }


    /**
     * 导入流程文件
     * <p>
     * 当每个key的流程第一次部署时，指定版本为1。对其后所有使用相同key的流程定义，
     * 部署时版本会在该key当前已部署的最高版本号基础上加1。key参数用于区分流程定义
     *
     * @param name
     * @param category
     * @param in
     */
    @Override
    public void importFile(String name, String category, InputStream in) {
        Deployment deploy = repositoryService.createDeployment().addInputStream(name + BPMN_FILE_SUFFIX, in).name(name).category(category).deploy();
        ProcessDefinition definition = repositoryService.createProcessDefinitionQuery().deploymentId(deploy.getId()).singleResult();
        repositoryService.setProcessDefinitionCategory(definition.getId(), category);

    }

    /**
     * 读取xml
     *
     * @param deployId
     * @return
     */
    @Override
    public AjaxResult readXml(String deployId) throws IOException {
        ProcessDefinition definition = repositoryService.createProcessDefinitionQuery().deploymentId(deployId).singleResult();
        InputStream inputStream = repositoryService.getResourceAsStream(definition.getDeploymentId(), definition.getResourceName());
        String result = IOUtils.toString(inputStream, StandardCharsets.UTF_8.name());
        return AjaxResult.success("", result);
    }

    /**
     * 读取xml
     *
     * @param deployId
     * @return
     */
    @Override
    public InputStream readImage(String deployId) {
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().deploymentId(deployId).singleResult();
        //获得图片流
        DefaultProcessDiagramGenerator diagramGenerator = new DefaultProcessDiagramGenerator();
        BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefinition.getId());
        //输出为图片
        return diagramGenerator.generateDiagram(
                bpmnModel,
                "png",
                Collections.emptyList(),
                Collections.emptyList(),
                "宋体",
                "宋体",
                "宋体",
                null,
                1.0,
                false);

    }

    /**
     * 根据流程定义ID启动流程实例
     *
     * @param flowTaskVo 发起流程信息
     * @return
     */
    @Override
    public AjaxResult startProcessInstanceById(FlowTaskVo flowTaskVo) {
        try {
            // 根据流程定义ID获取流程定义
            ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionId(flowTaskVo.getProcDefId())
                    .singleResult();
            // 判断流程实例是否存在
            if (Objects.isNull(processDefinition)) {
                return AjaxResult.error("流程实例不存在!");
            }
            // 判断流程是否被挂起
            if (processDefinition.isSuspended()) {
                return AjaxResult.error("流程已被挂起,请先激活流程!");
            }
            // 获取流程模型
            BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefinition.getId());
            Process mainProcess = bpmnModel.getMainProcess();
            // 设置流程任务抄送人员监听器
            FlowableUtils.addCopyTaskListener(mainProcess);
            // 是否需要重填表单
            String refill = mainProcess.getAttributeValue(ProcessConstants.NAMASPASE, ProcessConstants.PROCESS_CUSTOM_REFILL);
            // 设置当前用户ID
            identityService.setAuthenticatedUserId(SecurityUtils.getLoginUser().getUserId().toString());
            if (StringUtils.isNotBlank(refill) && "true".equals(refill)) {
                // TODO 处理发起人节点后的下一任务审批人
                handleRefillApproval(flowTaskVo.getVariables());
                flowTaskVo.getVariables().put(ProcessConstants.PROCESS_INITIATOR, "");
                // 流程发起时 直接完成第一个节点(流程配置时,第一个任务节点应设置为表单录入)
                ProcessInstance processInstance = runtimeService.startProcessInstanceById(processDefinition.getId(), flowTaskVo.getVariables());
                Task task = taskService.createTaskQuery().includeProcessVariables().processInstanceId(processInstance.getProcessInstanceId()).singleResult();
                if (Objects.nonNull(task)) {
                    // 发起人节点设置任务执行人和意见
                    taskService.addComment(task.getId(), processInstance.getProcessInstanceId(), FlowComment.SUBMIT.getType(), flowTaskVo.getComment());
                    // 发起人任务设置表单key信息 ,后续退回,驳回任务时可以根据该字段初始化表单
                    if (StringUtils.isBlank(task.getFormKey())) {
                        SysForm sysForm = sysDeployFormService.selectSysDeployFormByDeployId(processInstance.getDeploymentId());
                        if (Objects.nonNull(sysForm)) {
                            task.setFormKey(sysForm.getFormId().toString());
                            taskService.saveTask(task);
                        }
                    }
                    // 流程任务接收人设置为固定的参数,用来标识该任务节点是申请人节点任务,避免已办任务中出现自己申请的节点
                    taskService.setAssignee(task.getId(), ProcessConstants.PROCESS_INITIATOR);
                    taskService.complete(task.getId(), flowTaskVo.getVariables());
                }
            } else {
                flowTaskVo.getVariables().put(ProcessConstants.PROCESS_INITIATOR, SecurityUtils.getLoginUser().getUserId());
                runtimeService.startProcessInstanceById(processDefinition.getId(), flowTaskVo.getVariables());
            }
            return AjaxResult.success("任务已发起");
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("任务申请错误");
        }
    }

    /**
     * 处理发起人节点后的下一任务审批人
     * TODO: 暂时不处理下一节点是会签任务情况,流程设计时,先避免这种情况
     * 被退回/驳回任务后,申请人重新发起不需要选择任务接收人
     * 单独设置下一步任务处理人的变量，重新申请任务时，可以读取这个值，赋值给流程任务接收人
     * @param processVariables 流程变量
     */
    private void handleRefillApproval(Map<String, Object> processVariables){
        // 读取流程变量中下一步任务接收人并赋值给指定的流程变量
        processVariables.put(ProcessConstants.PROCESS_REFILL_APPROVAL,processVariables.get(ProcessConstants.PROCESS_APPROVAL));
    }

    /**
     * 读取流程模型配置
     *
     * @param procDefId 流程模型编号
     */
    private String getProcessSetting(String procDefId) {
        BpmnModel bpmnModel = repositoryService.getBpmnModel(procDefId);
        Process mainProcess = bpmnModel.getMainProcess();
        // 退回, 驳回流程后是否需要重新填写表单,此时设计流程时,第一个任务节点必须强制性的设置为申请人节点
        return mainProcess.getAttributeValue(ProcessConstants.NAMASPASE, ProcessConstants.PROCESS_CUSTOM_REFILL);
    }


    /**
     * 激活或挂起流程定义
     *
     * @param state    状态
     * @param deployId 流程部署ID
     */
    @Override
    public void updateState(Integer state, String deployId) {
        ProcessDefinition procDef = repositoryService.createProcessDefinitionQuery().deploymentId(deployId).singleResult();
        // 激活
        if (state == 1) {
            repositoryService.activateProcessDefinitionById(procDef.getId(), true, null);
        }
        // 挂起
        if (state == 2) {
            repositoryService.suspendProcessDefinitionById(procDef.getId(), true, null);
        }
    }


    /**
     * 删除流程定义
     *
     * @param deployId 流程部署ID act_ge_bytearray 表中 deployment_id值
     */
    @Override
    public void delete(String deployId) {
        // true 允许级联删除 ,不设置会导致数据库外键关联异常
        repositoryService.deleteDeployment(deployId, true);
    }


}
